package com.fjh.springboot_01.controller;

import com.fjh.springboot_01.pojo.lesson.Lesson;
import com.fjh.springboot_01.pojo.lesson.PageBean;
import com.fjh.springboot_01.pojo.Result;
import com.fjh.springboot_01.service.LessonService;
import com.fjh.springboot_01.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/lesson")
public class LessonController {
    @Autowired
    private LessonService lessonService;

    @PostMapping
    public Result add(@RequestBody @Validated Lesson lesson) {
        try {
            // 打印接收到的课程数据
            System.out.println("接收到的课程数据: " + lesson);
            System.out.println("视频URL: " + lesson.getVideoUrl());
            System.out.println("课程分类ID: " + lesson.getCategoryId());
            System.out.println("课程标题: " + lesson.getTitle());
            System.out.println("课程内容: " + lesson.getContent());
            System.out.println("课程状态: " + lesson.getState());
            
            // 验证课程状态
            if (lesson.getState() == null || (!lesson.getState().equals("已发布") && !lesson.getState().equals("草稿"))) {
                return Result.error("课程状态必须是'已发布'或'草稿'");
            }
            
            // 验证必填字段
            if (lesson.getTitle() == null || lesson.getTitle().trim().isEmpty()) {
                return Result.error("课程标题不能为空");
            }
            if (lesson.getContent() == null || lesson.getContent().trim().isEmpty()) {
                return Result.error("课程内容不能为空");
            }
            if (lesson.getCoverImg() == null || lesson.getCoverImg().trim().isEmpty()) {
                return Result.error("课程封面不能为空");
            }
            if (lesson.getVideoUrl() == null || lesson.getVideoUrl().trim().isEmpty()) {
                return Result.error("课程视频不能为空");
            }
            
            lessonService.add(lesson);
            return Result.success();
        } catch (Exception e) {
            // 打印异常信息
            System.err.println("添加课程失败，错误信息：");
            e.printStackTrace();
            return Result.error("添加课程失败：" + e.getMessage());
        }
    }

    @GetMapping
    public Result<PageBean<Lesson>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer userId
    ) {
        PageBean<Lesson> pb = lessonService.list(pageNum, pageSize, categoryId, keyword, userId);
        return Result.success(pb);
    }

    @DeleteMapping
    public Result delete(Integer id) {
        lessonService.deleteById(id);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody @Validated Lesson lesson) {
        try {
            // 打印接收到的更新数据
            System.out.println("接收到的更新数据: " + lesson);
            System.out.println("课程ID: " + lesson.getId());
            System.out.println("视频URL: " + lesson.getVideoUrl());
            System.out.println("课程分类ID: " + lesson.getCategoryId());
            System.out.println("课程标题: " + lesson.getTitle());
            System.out.println("课程内容: " + lesson.getContent());
            System.out.println("课程状态: " + lesson.getState());

            // 基本验证
            if (lesson.getId() <= 0) {
                return Result.error("无效的课程ID");
            }

            // 验证课程状态
            if (lesson.getState() == null || (!lesson.getState().equals("已发布") && !lesson.getState().equals("草稿"))) {
                return Result.error("课程状态必须是'已发布'或'草稿'");
            }

            // 验证必填字段
            if (lesson.getTitle() == null || lesson.getTitle().trim().isEmpty()) {
                return Result.error("课程标题不能为空");
            }
            if (lesson.getContent() == null || lesson.getContent().trim().isEmpty()) {
                return Result.error("课程内容不能为空");
            }
            if (lesson.getCoverImg() == null || lesson.getCoverImg().trim().isEmpty()) {
                return Result.error("课程封面不能为空");
            }
            if (lesson.getVideoUrl() == null || lesson.getVideoUrl().trim().isEmpty()) {
                return Result.error("课程视频不能为空");
            }
            if (lesson.getCategoryId() == null) {
                return Result.error("课程分类不能为空");
            }

            lessonService.update(lesson);
            return Result.success();
        } catch (Exception e) {
            // 打印详细的错误堆栈
            System.err.println("更新课程失败，详细错误：");
            e.printStackTrace();
            return Result.error("更新课程失败：" + e.getMessage());
        }
    }

    /**
     * 管理员专用接口 - 获取所有课程
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @param categoryId 分类ID
     * @param keyword 关键词
     * @param state 课程状态
     * @return 课程列表
     */
    @GetMapping("/admin/list")
    public Result<PageBean<Lesson>> adminList(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String state
    ) {
        // 验证管理员权限
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userRole = (Integer) map.get("role");
        if (userRole == null || userRole != 2) {
            return Result.error("无权限访问");
        }
        
        // 使用现有的list方法，传入null作为userId表示不限制创建者
        PageBean<Lesson> pb = lessonService.list(pageNum, pageSize, categoryId, keyword, null);
        return Result.success(pb);
    }
    
    /**
     * 管理员专用接口 - 更新课程状态
     * @param id 课程ID
     * @param state 新状态
     * @return 更新结果
     */
    @PatchMapping("/admin/state")
    public Result updateLessonState(Integer id, String state) {
        // 验证管理员权限
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userRole = (Integer) map.get("role");
        if (userRole == null || userRole != 2) {
            return Result.error("无权限访问");
        }
        
        // 验证状态值
        if (state == null || (!state.equals("已发布") && !state.equals("草稿"))) {
            return Result.error("课程状态必须是'已发布'或'草稿'");
        }
        
        try {
            // 获取课程对象
            Lesson lesson = lessonService.getLessonById(id);
            if (lesson == null) {
                return Result.error("课程不存在");
            }
            
            // 更新状态
            lesson.setState(state);
            lessonService.update(lesson);
            return Result.success();
        } catch (Exception e) {
            return Result.error("更新课程状态失败：" + e.getMessage());
        }
    }
}